# coding=utf-8
import cv2
import numpy as np

import detector

# 在图片上画直线段，
# https://blog.csdn.net/weixin_42618420/article/details/106097270
def draw_lines(img, lines, color, width):
    img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    for line in lines[0]:
        x0 = int(round(line[0][0]))
        y0 = int(round(line[0][1]))
        x1 = int(round(line[0][2]))
        y1 = int(round(line[0][3]))
        cv2.line(img_rgb, (x0, y0), (x1,y1), color, width, cv2.LINE_AA)
    return img_rgb
# 画点
# 传入的点是浮点型，但画出的点只能在整数的坐标上
def draw_points(img, points, color, radius=3, line_width=8):
    img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    points = np.round(points).astype(int)
    for point in points:
        point[0]
        cv2.circle(img_rgb, point, radius, color, line_width)
    return img_rgb

def get_slope(line):
    x0 = line[0][0]
    y0 = line[0][1]
    x1 = line[0][2]
    y1 = line[0][3]
    dy = y1 - y0
    dx = x1 - x0
    return dy / dx

def calc_mean_slope(roi):
    # 创建一个LSD对象
    lsd = cv2.createLineSegmentDetector(0)
    # 执行检测结果
    dlines = lsd.detect(roi)
    slopes = []
    for dline in dlines[0]:
        slopes.append(get_slope(dline))
    slopes = np.array(slopes)
    new_slopes = detector.remove_outliers_sigma(slopes,1)
    return new_slopes.mean()

if __name__ == "__main__":

    single_img_path = "../fabric-defect/麻皮/T03825_00.bmp"
    img = detector.cv_read(single_img_path)
    detector.cv_show('img', img)

    # 创建一个LSD对象
    lsd = cv2.createLineSegmentDetector(0)
    # 执行检测结果
    dlines = lsd.detect(img)
    # 绘制检测结果
    draw_lines(img, dlines, (255,255,255), 2)

    # 显示并保存结果
    # cv2.imwrite('test3_r.jpg', img)
    detector.cv_show("LSD", img,block=True)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    # https://blog.csdn.net/m0_51233386/article/details/124171578